using Digitalmes.Domain.Entities.Mes.Processes;

namespace Digitalmes.Application.Mes.Processes.RoutingSteps.Commands;

/// <summary>
/// 工艺路线步骤删除命令。
/// </summary>
/// <param name="RoutingId"></param>
public sealed record DeleteRoutingStepCommand(long RoutingStepId) : IRequest<IResult<bool>>;

internal sealed class DeleteRoutingStepCommandHandler(IRepository<ProcRoutingStep> repo) : IRequestHandler<DeleteRoutingStepCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(DeleteRoutingStepCommand request, CancellationToken cancellationToken)
    {
        var step = await repo.GetByIdAsync(request.RoutingStepId, cancellationToken);
        if (step == null)
        {
            return Result.From(true);
        }

        // 设置前一工序的后置步骤和后一工序的前置步骤
        // 删除时不用重置序号
        List<ProcRoutingStep> steps = new(2);
        var prevStep = await repo.FirstOrDefaultAsync(m => m.NextStepId == step.Id, cancellationToken);
        var nextStep = await repo.FirstOrDefaultAsync(m => m.PrevStepId == step.Id, cancellationToken);
        if (prevStep != null)
        {
            prevStep.NextStepId = nextStep?.Id;
            steps.Add(prevStep);
        }
        if (nextStep != null)
        {
            nextStep.PrevStepId = prevStep?.Id;
            steps.Add(nextStep);
        }

        if (steps.Count > 0)
        {
            await repo.UpdateAsync(steps, m => new
            {
                m.PrevStepId,
                m.NextStepId,
                m.UpdatedBy,
                m.UpdatedTime,
            }, cancellationToken);
        }

        var ok = await repo.DeleteByIdAsync(request.RoutingStepId, cancellationToken);
        return Result.From(ok);
    }
}
